/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.jctc.els.modules.biz.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jctc.els.common.config.BladeFileConfiguration;
import org.jctc.els.modules.biz.excel.ElssystemlogExcel;
import org.jctc.els.modules.biz.service.ILogApiService;
import org.jctc.els.modules.biz.vo.LogApiVO;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.log.model.LogApi;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author Chill
 */
@NonDS
@ApiIgnore
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_LOG_NAME + "/api")
@Api(value = "日志", tags = "日志表接口")
public class LogApiController extends BladeController {

	private final ILogApiService logService;

	private BladeFileConfiguration bladeFileConfiguration;

	/**
	 * 查询单条
	 *//*
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入logApi")
	public R<LogApi> detail(LogApi log) {
		return R.data(logService.getOne(Condition.getQueryWrapper(log)));
	}

	*//**
	 * 查询多条(分页)
	 *//*
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入logApi")
	public R<IPage<LogApi>> list(@ApiIgnore @RequestParam Map<String, Object> log, Query query) {
		IPage<LogApi> pages = logService.page(Condition.getPage(query.setDescs("create_time")), Condition.getQueryWrapper(log, LogApi.class));
		return R.data(pages);
	}*/

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入logApi")
	public R<LogApi> detail(@RequestParam("id")Long id) {
		LogApi detail = logService.selectById(id);
		return R.data(detail);
	}

	/**
	 * 分页 培训班信息表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入logApi")
	public R<IPage<LogApi>> list(
		@RequestParam(value = "pageNum") Integer pageNum,
		@RequestParam(value = "pageSize") Integer pageSize,
		@RequestParam(value = "createdBy",required = false) String createdBy,
		@RequestParam(value = "logType",required = false) String logType,
		@RequestParam(value = "createTime",required = false) String createTime) {
		IPage<LogApi> pages = logService.selectAllPage(pageNum, pageSize,createdBy,logType,createTime,0L);
		return R.data(pages);
	}


	@GetMapping("/listOther")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入logApi")
	public R<IPage<LogApi>> listOther(
		@RequestParam(value = "pageNum") Integer pageNum,
		@RequestParam(value = "pageSize") Integer pageSize,
		@RequestParam(value = "createdBy",required = false) String createdBy,
		@RequestParam(value = "logType",required = false) String logType,
		@RequestParam(value = "createTime",required = false) String createTime) {
		IPage<LogApi> pages = logService.selectAllPageOther(pageNum, pageSize,createdBy,logType,createTime);
		return R.data(pages);
	}

	/**
	 * 自定义分页 培训班信息表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "分页", notes = "传入logApi")
	public R<IPage<LogApiVO>> page(LogApiVO logApi, Query query) {
		IPage<LogApiVO> pages = logService.selectLogApiPage(Condition.getPage(query), logApi);
		return R.data(pages);
	}


	/**
	 *   导出
	 *
	 * **/
	@GetMapping("/export-systemlog")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "导出数据", notes = "传入logApi")
	public void exportSystemlog(@ApiIgnore @RequestParam Map<String,Object> projects,HttpServletResponse response){
//		增删改实体类
		   QueryWrapper <LogApi> queryWrapper= Condition.getQueryWrapper(projects,LogApi.class);
// 导出
		List<ElssystemlogExcel> list = logService.ExportPage(queryWrapper);
		ExcelUtil.export(response, "系统日志数据" + DateUtil.time(), "系统日志数据表", list, ElssystemlogExcel.class);


	}

	/**
	 * 导入
	 *
	 *
	 * **/
	@PostMapping("import-Systemlog")
//	@ApiOperationSupport(order = 6)
	@ApiOperation(value="导入数据",notes = "传入logApi")
	public R importProjects(HttpServletRequest request){
		R result = new R();
		String fileName = "";
		//创建一个“硬盘文件条目工厂”对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
		factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
		//设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
		factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
		//创建核心对象
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		//设置最大可支持的文件大小（10MB）
		fileUpload.setFileSizeMax(1024 * 1024 * 10);
		//设置转换时使用的字符集
		fileUpload.setHeaderEncoding("UTF-8");
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				List<FileItem> fileItems = fileUpload.parseRequest(request);
				for (FileItem fileItem : fileItems) {
					if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
						//获取字段名
						String fieldName = fileItem.getFieldName();
						//获取字段值，并解决乱码
						String fieldValue = fileItem.getString("UTF-8");
						System.out.println(fieldName + " : " + fieldValue);

					} else {//判断该FileItem为一个文件

						System.out.println("Start to upload file!");
						//获取文件名
						fileName = fileItem.getName();
						System.out.println("fileName : " + fileName);
						//获取文件大小
						long fileSize = fileItem.getSize();
						MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
						logService.importSystemlog(multipartFile, request);
						fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return  result;


	}

}
